﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTunesFastForward.Amazon;

namespace iTunesFastForward
{
    class AmazonWebService
    {
        string accessKey = "1EFD7B97X10D8P2KRT02";

        public List<AlbumCover> GetAlbumCovers(string keywords)
        {
            AWSECommerceServicePortTypeClient awse = new AWSECommerceServicePortTypeClient();

            List<AlbumCover> covers = new List<AlbumCover>();

            ItemSearch search = new ItemSearch();
            //search.AssociateTag = accessKey;
            search.AWSAccessKeyId = accessKey;

            ItemSearchRequest request = new ItemSearchRequest();

            // Fill request object with request parameters
            request.ResponseGroup = new string[] { "Medium", "Images" };

            // Set SearchIndex and Keywords 
            request.SearchIndex = "Music";
            request.Keywords = keywords;

            // Set the request on the search wrapper
            search.Request = new ItemSearchRequest[] { request };

            //Send the request and store the response 
            //in response
            ItemSearchResponse response = awse.ItemSearch(search);

            foreach (Items items in response.Items)
            {
                if (items.Item == null)
                    return null;

                foreach (Item item in items.Item)
                {

                    if (item.ItemAttributes != null && item.MediumImage != null)
                    {

                        string artist = null;
                        if (item.ItemAttributes.Artist != null)
                            artist = string.Join(" - ", item.ItemAttributes.Artist);

                        AlbumCover cover = new AlbumCover
                        {
                            Album = item.ItemAttributes.Title,
                            Artist = artist,
                            Year = item.ItemAttributes.ReleaseDate,
                            ImageURLTiny = item.SmallImage == null ? null : item.SmallImage.URL,
                            ImageURLMedium = item.MediumImage == null ? null : item.MediumImage.URL,
                            ImageURLBig = item.LargeImage == null ? null : item.LargeImage.URL
                        };
                        cover.FetchCovers(false);
                        covers.Add(cover);
                    }
                }
            }


            return covers;
        }

    }
}
